package fileDemo;

import java.io.File;
import java.util.Scanner;

public class Demo16 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要扫描的目录：");
        String filename = sc.next();
        File file = new File(filename);
        if (!file.isDirectory()) {
            System.out.println("您输⼊的不是目录，退出");
            return;
        }
        System.out.println("请输入要删除的文件：");
        String deleteName = sc.next();
        traversefile(file, deleteName);
    }

    private static void traversefile(File file, String deleteName) {
        //1.遍历该目录下的文件
        File[] files = file.listFiles();
        //2.判断是否目录是否为空
        if (files == null || files.length == 0) {
            return;
        }
        for (File f : files) {
            //判断是否是目录还是普通文件
            if (f.isDirectory()) {
                traversefile(f, deleteName);
            } else {
                deletefile(f, deleteName);
            }
        }

    }

    private static void deletefile(File f, String deleteName) {
        if (f.getName().contains(deleteName)) {
            System.out.println("找到包含关键字的文件，是否删除"+f.getName()+"文件，(y/n)");
            Scanner sc = new Scanner(System.in);
            String answer = sc.next();
            if (answer.equals("y")) {
                f.delete();
                System.out.println("文件删除！！！");
            } else {
                return;
            }
        }
    }
}
